/**
 * 
 * 广州锐鹏计算机科技有限公司（www.ruipengkj.com）
 * 
 * 
 * Copyright (c) 2011-2012 RUIPENGKJ.Co.Ltd. All rights reserved.
 * 
 * */
package com.ruipengkj.view.purchaseView;
/**
 * 说明：
 * 进货单添加窗口
 * @Author：黄盛强
 * @Date：2012-03-26
 */
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableCellEditor;

import com.ruipengkj.ApplicationContext;
import com.ruipengkj.bean.TBillDetail;
import com.ruipengkj.bean.TEmployee;
import com.ruipengkj.bean.TPurchase;
import com.ruipengkj.bean.TStockInOut;
import com.ruipengkj.bean.TStore;
import com.ruipengkj.bean.TSupplier;
import com.ruipengkj.commons.BuildSpringApplication;
import com.ruipengkj.commons.util.IDNameBean;
import com.ruipengkj.commons.util.TabelUtil;
import com.ruipengkj.commons.util.UUID;
import com.ruipengkj.commons.util.Util;
import com.ruipengkj.component.JComboBoxPOJO;
import com.ruipengkj.component.JLabelJComboBoxComponent;
import com.ruipengkj.component.JLabelJTextFieldComponent;
import com.ruipengkj.component.JPanelFlowLayoutComponent;
import com.ruipengkj.component.RPJButtonRoundBlue;
import com.ruipengkj.component.RPJButtonRoundOrager;
import com.ruipengkj.component.RPJButtonWhite;
import com.ruipengkj.component.comboBox.CommodityJComboBoxTableBuy;
import com.ruipengkj.component.jdialog.BorderJPanel;
import com.ruipengkj.component.jdialog.IDialog;
import com.ruipengkj.component.jpanel.RepeatImagePanel;
import com.ruipengkj.factory.ImageFactory;
import com.ruipengkj.model.PuchaseEnterAddModel;
import com.ruipengkj.service.TBillDetailService;
import com.ruipengkj.service.TCommodityService;
import com.ruipengkj.service.TEmployeeService;
import com.ruipengkj.service.TPurchaseService;
import com.ruipengkj.service.TStockInOutService;
import com.ruipengkj.service.TStoreService;
import com.ruipengkj.service.TSupplierService;

public class PurchaseEnterAddOrModifyPanel extends IDialog implements TableModelListener {

	private static final long serialVersionUID = 1L;
	
	private JLabelJTextFieldComponent purchaseID;//采购编号
	
	private JLabelJComboBoxComponent vendor = null;//供应商
	private JLabelJComboBoxComponent store;//仓库
	
	private JLabelJComboBoxComponent buyer = null; //采购员
	
	private JLabelJTextFieldComponent numTF;//数量
	private JLabelJTextFieldComponent moneyTF;//金额
	private JLabelJTextFieldComponent storageQuantityTF;//存库量
	
	private JButton addButton; //添加行
	private JButton delButton; //删除行
	private JButton saveExitButton; //保存退出
	private JButton saveButton; //保存新增
	private JButton exitButton; //直接退出
	
	private JTable table;
	private JScrollPane tableJsp;
	private PuchaseEnterAddModel puchaseEnterAddModel;
	
	private TBillDetailService tBillDetailService;//单据商品明细
	private TSupplierService tSupplierService;//供货商单
	private TStoreService tStoreService;//仓库
	private TPurchaseService tPurchaseService;//采购
	private TStockInOutService tStockInOutService;//入/出库单
	private TCommodityService tCommodityService;//商品
	private TEmployeeService tEmployeeService;//员工
	private TPurchase tPurchase;
	public boolean isSuccess=false;
	private CommodityJComboBoxTableBuy cbox;
	public PurchaseEnterAddOrModifyPanel(JDialog jd, String title, boolean b) {
		super(jd, title, b);
		tSupplierService = BuildSpringApplication.getInstance().getTSupplierServiceImpl();
		tPurchaseService = BuildSpringApplication.getInstance().getTPurchaseServiceImpl();
		tBillDetailService = BuildSpringApplication.getInstance().getTBillDetailServiceImpl();
		tStockInOutService = BuildSpringApplication.getInstance().getTStockInOutServiceImpl();
		tStoreService = BuildSpringApplication.getInstance().getTStoreServiceImpl();
		tCommodityService = BuildSpringApplication.getInstance().getTCommodityServiceImpl();
		tEmployeeService=BuildSpringApplication.getInstance().getTEmployeeServiceImpl();
		this.init();
		this.initListener();
		this.setSize(900, 600);
		this.setResizable(false);
		this.setLocationRelativeTo(null);
		
	}
	private void init() {
		puchaseEnterAddModel = new PuchaseEnterAddModel();
		puchaseEnterAddModel.setEditable(true);
		table=uiFactory.createRPJTable(puchaseEnterAddModel, this, this, 30, JLabel.CENTER);
		cbox = new CommodityJComboBoxTableBuy();
		cbox.setBorder(null);
		TableCellEditor edt = new DefaultCellEditor(cbox);
		table.getColumnModel().getColumn(2).setCellEditor(edt);
		table.getColumnModel().getColumn(3).setCellEditor(edt);
		tableJsp=uiFactory.createJScrollPane(table);
		
		TabelUtil.hideTableColumn(0, table);
		
		JPanel main_jp=new BorderJPanel(new BorderLayout());
		main_jp.setBackground(Util.PANEL_COLOR);
		main_jp.add(this.initTop(), BorderLayout.NORTH);
		main_jp.add(tableJsp, BorderLayout.CENTER);
		main_jp.add(this.initTail(), BorderLayout.SOUTH);
		this.add(main_jp);
		main_jp.setCursor(Util.CURSOR_DEFAULT);
	}
	//头部
	private JPanel initTop() {
		purchaseID = new JLabelJTextFieldComponent("采购编号：", 30);
		purchaseID.getText().setText(UUID.GenUUID15());
		purchaseID.getText().setEditable(false);
		store = new JLabelJComboBoxComponent("进货仓库：", new String[]{}, 188);
		store.addElement(new JComboBoxPOJO("请选择……"));
		JPanel jp1 = new JPanelFlowLayoutComponent(new Component[]{purchaseID, store}, FlowLayout.LEFT);
		
		vendor = new JLabelJComboBoxComponent("供 应 商：", new String[]{},188);
		vendor.addElement(new JComboBoxPOJO("请选择……"));
		buyer = new JLabelJComboBoxComponent("采  购  员：", new String[]{},180);
		buyer.addElement(new IDNameBean("0", "请选择"));
		JLabelJTextFieldComponent operator = new JLabelJTextFieldComponent("操 作 员：", 30);
		operator.getText().setText(ApplicationContext.OPERATOR_NAME);
		operator.getText().setEditable(false);
		JPanel jp7 = new JPanelFlowLayoutComponent(new Component[]{vendor, buyer, operator}, FlowLayout.LEFT);
		
		JPanel top_panel = new RepeatImagePanel(ImageFactory.loadImage(ImageFactory.DIALOG_TOP_BG_2).getImage());
		top_panel.setLayout(new GridLayout(2, 1));
		top_panel.add(jp1);
		top_panel.add(jp7);
		return top_panel;
	}
	//底部
	private JPanel initTail() {
		JPanel tail_panel = new RepeatImagePanel(ImageFactory.loadImage(ImageFactory.DIALOG_TOP_BG_2).getImage());
		tail_panel.setLayout(new GridLayout(2, 1));
		
		JPanel jp8 = uiFactory.createFlowJPanel(FlowLayout.LEFT);
		addButton = new RPJButtonRoundBlue("添加行");
		delButton = new RPJButtonRoundOrager("删除行");
		jp8.add(addButton);
		jp8.add(delButton);
		
		JPanel jp1 = uiFactory.createFlowJPanel(FlowLayout.LEFT);
		numTF = new JLabelJTextFieldComponent("合计：数量", 10);
		numTF.getText().setText("0");
		numTF.getText().setEditable(false);
		moneyTF = new JLabelJTextFieldComponent("金额：", 10);
		moneyTF.getText().setText("0.0");
		moneyTF.getText().setEditable(false);
		storageQuantityTF = new JLabelJTextFieldComponent("当前库存量：", 10);
		storageQuantityTF.getText().setText("0");
		storageQuantityTF.getText().setEditable(false);
		jp1.add(numTF);
		jp1.add(moneyTF);
		jp1.add(storageQuantityTF);
		
		saveExitButton = new RPJButtonWhite("保存退出(Ctrl+S)");
		saveButton = new RPJButtonWhite("保存新增(Ctrl+I)");
		exitButton = new RPJButtonWhite("直接退出(Ctrl+Q)");
		jp1.add(saveExitButton);
		jp1.add(saveButton);
		jp1.add(exitButton);
		
		tail_panel.add(jp8);
		tail_panel.add(jp1);
		return tail_panel;
	}
	
	@Override
	protected java.awt.Dimension getTitleSize() {
		return new Dimension(126, 29);
	};
	
	//添加事件监听器
	private void initListener() {
		addButton.addActionListener(this);
		delButton.addActionListener(this);
		saveExitButton.addActionListener(this); //保存退出
		saveExitButton.registerKeyboardAction(this, KeyStroke.getKeyStroke(KeyEvent.VK_I, KeyEvent.CTRL_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW);
		saveButton.addActionListener(this); //保存新增
		saveButton.registerKeyboardAction(this, KeyStroke.getKeyStroke(KeyEvent.VK_S, KeyEvent.CTRL_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW);
		exitButton.addActionListener(this); //直接退出
		exitButton.registerKeyboardAction(this, KeyStroke.getKeyStroke(KeyEvent.VK_Q, KeyEvent.CTRL_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW);
		store.getBox().addActionListener(this);
		puchaseEnterAddModel.addTableModelListener(this);
	}
	
	//数据库中的数据放入list（读取数据）
	private Runnable queryBillDetail=new Runnable() {
		@Override
		public void run() {
			try {
				addButton.setEnabled(false);
				delButton.setEnabled(false);
				saveExitButton.setEnabled(false);
				saveButton.setEnabled(false);
				TBillDetail tBillDetail = new TBillDetail();
				tBillDetail.setBillID(tPurchase.getPurchaseID());
				tBillDetail.setBillType(ApplicationContext.BILL_BILLTYPE1);
				List<TBillDetail> billDetailList = tBillDetailService.findService(tBillDetail);
				if (billDetailList != null &&  billDetailList.size()!= 0) {
					int length = billDetailList.size();
					for (int i = 0; i < length; ++i) {
						//获取商品 以便查看
						billDetailList.get(i).setCommodity(tCommodityService.findByIdService(billDetailList.get(i).getCommodityID()));
						puchaseEnterAddModel.addBillDetail(billDetailList.get(i));
					}
				}
				ApplicationContext.countStoreNumber(puchaseEnterAddModel.findAllBillDetailList(), null, null, numTF.getText(), moneyTF.getText(), storageQuantityTF.getText());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};
	
	public void showDialog(String purchaseID) {
		try {
			TPurchase tPurchase = null;
			if (purchaseID != null && !purchaseID.equals(""))
				tPurchase = tPurchaseService.getByIdService(purchaseID);
			showDialog(tPurchase);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void showDialog(TPurchase tPurchase) {
		if(tPurchase!=null){//读取进货表中的数据
			puchaseEnterAddModel.setEditable(false);
			this.tPurchase=tPurchase;
			purchaseID.getText().setText(tPurchase.getPurchaseID());//采购ID
			//供货商
			if (tPurchase.getTSupplier() != null && tPurchase.getTSupplier().getSupplierID() != null){
				vendor.addElement(new JComboBoxPOJO(tPurchase.getTSupplier().getSupplierID(), tPurchase.getTSupplier().getName(), tPurchase.getTSupplier()));
				vendor.getBox().setSelectedIndex(1);
			}
			TStockInOut tStockInOut = new TStockInOut();//取出   出入库存单
			tStockInOut.setSourceType((byte)1);
			tStockInOut.setSource(tPurchase.getPurchaseID());
			try {//取出出入库存单中的仓库
				List<TStockInOut> tStockInOutlist = tStockInOutService.findService(tStockInOut);
				TStore tStore = tStockInOutlist.get(0).getTStore();
				if (tStore != null && tStore.getStoreID() != null) {
					store.addElement(new JComboBoxPOJO(tStore.getStoreID(), tStore.getName(), tStore));
					store.getBox().setSelectedIndex(1);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			SwingUtilities.invokeLater(queryBillDetail);
		} else {
			SwingUtilities.invokeLater(querySupplier);
			SwingUtilities.invokeLater(queryStore);
		}
		SwingUtilities.invokeLater(queryEmp);
		this.setVisible(true);
	}
	
	
	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource() == addButton) {
			//添加行
			if (store.getBox().getSelectedIndex() == 0) {
				JOptionPane.showMessageDialog(null, "请先选择仓库！");
				return;
			}
			if (vendor.getBox().getSelectedIndex() == 0) {
				JOptionPane.showMessageDialog(null, "请先选择供应商！");
				return;
			}
			if (buyer.getBox().getSelectedIndex() == 0) {
				JOptionPane.showMessageDialog(null, "请先选择采购员！");
				return;
			}
			TBillDetail tBillDetail=new TBillDetail();
			tBillDetail.setDetailID(UUID.GenUUID15());
			tBillDetail.setBillID(purchaseID.getText().getText());
			tBillDetail.setNum(1);
			tBillDetail.setBillType(ApplicationContext.BILL_BILLTYPE1);
			puchaseEnterAddModel.addBillDetail(tBillDetail);
			TableCellEditor edt = new DefaultCellEditor(cbox);
			table.getColumnModel().getColumn(2).setCellEditor(edt);
			table.getColumnModel().getColumn(3).setCellEditor(edt);
		} else if(e.getSource() == delButton) {
			//删除行
			if(table.getRowCount()==0){
				JOptionPane.showMessageDialog(null, "当前数据为空");
				return;
			}else{
				List<Integer> ints=new ArrayList<Integer>();
				int select[] = table.getSelectedRows();
				if (select != null && select.length != 0) {
					for (int i = 0; i < select.length; ++i) {
						ints.add(select[i]);
					}
				}
				
//				for(int i=0;i<puchaseEnterAddModel.findAllBillDetailList().size();i++){
//					TBillDetail billDetail=puchaseEnterAddModel.findAllBillDetailList().get(i);
//					if(billDetail.isFlag()){
//						ints.add(i);
//					}
//				}
				if(ints.size()!=0){
					if(JOptionPane.showConfirmDialog(null, "是否要删除选中行？","提示",JOptionPane.OK_CANCEL_OPTION)==0){
						for(int i=ints.size()-1;i>=0;i--){
							puchaseEnterAddModel.delBillDetail(ints.get(i));
						}
					}
				}else{
					JOptionPane.showMessageDialog(null, "请先选择你需要删除的行");
				}
				ints.clear();
			}
		} else if(e.getSource() == saveExitButton) {
			//保存退出
			if(this.addPurchase()){
				this.dispose();
			}
		} else if(e.getSource() == saveButton) {
			//保存新增
			if(this.addPurchase()){
				puchaseEnterAddModel.clearAllBillDetail();
				purchaseID.getText().setText(UUID.GenUUID15());
				vendor.getBox().setSelectedIndex(0);
				buyer.getBox().setSelectedIndex(0);
				table.updateUI();
			}
		} else if(e.getSource() == exitButton) {
			if(Util.showConfirmDialog("是否要退出？")==0){
				this.dispose();
			}
		} else {
			super.actionPerformed(e);
		}
		
	}
	
	@Override
	public void mouseClicked(MouseEvent e) {
		if (e.getSource() == table) {
			table.updateUI();
			int row=table.getSelectedRow();
			if(row!=-1){
				Object obj=table.getValueAt(row, 2);
				if(obj!=null){
					JComboBoxPOJO storePO=(JComboBoxPOJO)store.getBox().getSelectedItem();
					ApplicationContext.countStoreNumber(puchaseEnterAddModel.findAllBillDetailList(), (TStore)storePO.getObject(), obj.toString(), numTF.getText(), moneyTF.getText(), storageQuantityTF.getText());
				}
			}
		}
	}
	//添加采购单
	private boolean addPurchase() {
		List<TBillDetail> modelList2=puchaseEnterAddModel.findAllBillDetailList();
		
		if (modelList2.size() <= 0) {
			JOptionPane.showMessageDialog(null, "请添加商品，在进行新增操作！");
			return false;
		}
		
		List<TBillDetail> modelList = new ArrayList<TBillDetail>();
		for (TBillDetail tb : modelList2) {
			modelList.add(tb);
		}
		
		//判断表格
		if(!ApplicationContext.ifBillDetail(modelList, null)){
			return false;
		}
		if (vendor.getBox().getSelectedIndex()==0) {
			JOptionPane.showMessageDialog(null, "请选择供应商！");
			return false;
		}
		if(store.getBox().getSelectedIndex()==0){
			JOptionPane.showMessageDialog(null, "请选择进货仓库！");
			return false;
		}
		if(buyer.getBox().getSelectedIndex()==0){
			JOptionPane.showMessageDialog(null, "请选择采购员！");
			return false;
		}
		if(tPurchase==null){
			tPurchase=new TPurchase();
		}
		IDNameBean bean=(IDNameBean)buyer.getBox().getSelectedItem();//采购员
		JComboBoxPOJO storePo=(JComboBoxPOJO)store.getBox().getSelectedItem();//仓库
		JComboBoxPOJO vendorPo=(JComboBoxPOJO)vendor.getBox().getSelectedItem();//供应商
		
		tPurchase.setPurchaseID(purchaseID.getText().getText().trim());
		tPurchase.setBuyer(bean.getStrId());
		tPurchase.setOperator(ApplicationContext.OPERATOR_ID);
		tPurchase.setTSupplier((TSupplier)vendorPo.getObject());
		tPurchase.setHappenTime(new Date());
		tPurchase.setAuditTime(new Date());
		try {
			ApplicationContext.TCommodityAvgPrice(modelList);
			tPurchaseService.saveOrUpdateService(tPurchase);
			ApplicationContext.addInOutBillDetailMoney(puchaseEnterAddModel.findAllBillDetailList(),(TStore)storePo.getObject(),ApplicationContext.STOCK_IN_OUT_SOURCE_TYPE1,ApplicationContext.STOCK_TYPE_IN,purchaseID.getText().getText().trim(),ApplicationContext.MONEYINOUT_TYPE_OUT,ApplicationContext.MONEYINOUT_SOURCE_TYPE1,bean.getStrId());
			BuildSpringApplication.getInstance().getTOpLogServiceImpl().addOpLogService("添加进货单信息");
			setSupplierData(modelList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		this.isSuccess = true;
		return true;
	}
	
	//更新供货商数量金额
	private void setSupplierData(List<TBillDetail> modelList) {
		int num = 0;
		double money = 0;
		for(int i = 0; i < modelList.size(); ++i) {
			TBillDetail billDetail=modelList.get(i);
			num += billDetail.getNum();
			money += (billDetail.getNum()*billDetail.getPrice());
		}
		JComboBoxPOJO po = (JComboBoxPOJO)vendor.getBox().getSelectedItem();
		if (po == null) {
			return;
		}
		TSupplier supplier = (TSupplier)po.getObject();
		supplier.setTotalNum(supplier.getTotalNum()+num);
		supplier.setTotalMoney(supplier.getTotalMoney()+money);
		try {
			tSupplierService.modifyService(supplier);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//读取供货商数据
	private Runnable querySupplier=new Runnable() {
		@Override
		public void run() {
			try {
				List<TSupplier> tSupplierList = tSupplierService.findValidService(null);
				if (tSupplierList != null && tSupplierList.size()!=0) {
					for(int i = 0; i < tSupplierList.size(); ++i) {
						TSupplier supplie=tSupplierList.get(i);
						vendor.addElement(new JComboBoxPOJO(supplie.getSupplierID(),supplie.getName(),supplie));
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};
	//读取仓库数据
	private Runnable queryStore=new Runnable() {
		@Override
		public void run() {
			try {
				List<TStore> tStoreList = tStoreService.findService(null);
				if (tStoreList != null && tStoreList.size()!=0) {
					int length = tStoreList.size();
					for(int i = 0; i < length; ++i) {
						TStore tStore=tStoreList.get(i);
						store.addElement(new JComboBoxPOJO(tStore.getStoreID(),tStore.getName(),tStore));
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};
	//读取采购员
	public Runnable queryEmp=new Runnable() {
		@Override
		public void run() {
			try {
				List<TEmployee> list=tEmployeeService.findService(null);
				if(list!=null&&list.size()!=0){
					for(int i=0;i<list.size();i++){
						TEmployee emp=list.get(i);
						buyer.addElement(new IDNameBean(emp.getEmployeeID(), emp.getName()));
						if(tPurchase!=null){
							if(emp.getEmployeeID().equals(tPurchase.getBuyer())){
								buyer.getBox().setSelectedIndex(i+1);//采购人
							}
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};
	@Override
	public void tableChanged(TableModelEvent arg0) {
		int row=table.getSelectedRow();
		if(row!=-1 && row < puchaseEnterAddModel.getRowCount()){
			Object obj=table.getValueAt(row, 2);
			if(obj!=null){
				JComboBoxPOJO storePO=(JComboBoxPOJO)store.getBox().getSelectedItem();
				ApplicationContext.countStoreNumber(puchaseEnterAddModel.findAllBillDetailList(), (TStore)storePO.getObject(), obj.toString(), numTF.getText(), moneyTF.getText(), storageQuantityTF.getText());
			}
		}
	}
	
	public static void main(String[] args) {
		PurchaseEnterAddOrModifyPanel dialog = new PurchaseEnterAddOrModifyPanel(null, "添加采购信息", true);
		dialog.setVisible(true);
	}
}